package com.atguigu.dao.impl;

import com.atguigu.dao.BaseDao;
import com.atguigu.dao.BookDao;
import com.atguigu.domain.Book;
import com.atguigu.domain.Page;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author dl
 * @create 2020-04-25-14:14
 */
public class BookDaoImpl extends BaseDao<Book> implements BookDao {

	@Override
	public List<Book> getAllBook() {
		String sql = "select * from bs_book";
		return getBeanList(sql);
	}

	@Override
	public boolean saveBook(Book book) {
		String sql = "insert into bs_book(name,author,price,sales,stock,img_path) values(?,?,?,?,?,?)";
		int update = update(sql, book.getName(), book.getAuthor(),
				book.getPrice(), book.getSales(), book.getStock(), book.getImgPath());
		return update > 0;
	}

	@Override
	public boolean updateBook(Book book) {
		String sql = "update bs_book set name=?,author=?,price=?,sales=?,stock=?,img_path=? where id=?";
		int update = update(sql, book.getName(), book.getAuthor(),
				book.getPrice(), book.getSales(), book.getStock(), book.getImgPath(),book.getId());
		return update > 0;
	}

	/**
	 * TODO c3p0 现在将 img_path 赋值给 bean 中的 imgPath?
	 * @param bookId
	 * @return
	 */
	@Override
	public Book getBookById(Integer bookId) {
		String sql = "select * from bs_book where id=?";
		return getBean(sql, bookId);
	}

	@Override
	public boolean delBook(Book book) {
		String sql = "delete from bs_book where id=?";
		int delete = update(sql, book.getId());
		return delete > 0;
	}

	@Override
	public List<Book> getItems(int queryIndex, int pageSize) {
		String sql = "select * from bs_book limit ?,?";
		return getBeanList(sql,queryIndex,pageSize);
	}

	@Override
	public Object queryCount() {
		String sql = "select count(*) from bs_book";
		return queryTotalCount(sql);
	}

	@Override
	public Object queryCountByPrice(BigDecimal minPrice, BigDecimal maxPrice) {
		String sql = "select count(*) from bs_book where price between ? and ?";
		return queryTotalCount(sql, minPrice , maxPrice);
	}

	@Override
	public List<Book> getItemsByPrice(int queryIndex, int pageSize, BigDecimal minPrice, BigDecimal maxPrice) {
		String sql = "select * from bs_book where price between ? and ? limit ?,?";
		return getBeanList(sql,minPrice,maxPrice,queryIndex,pageSize);
	}

	@Override
	public int updateBookStockAndSales(Integer bookId, Integer stock, Integer sales) {
		String sql = "update bs_book set sales=?,stock=? where id = ?";
		return update(sql,sales,stock,bookId);
	}
}
